package com.module.lemlin.custom

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration

class GridSpacingItemDecoration(
    //列数
    private var spanCount: Int,
    //间隔
    private val spacing: Int,
    //是否有头布局
    private val isHeader: Boolean = false,
    //是否包含边缘
    private val includeEdge: Boolean = true
) : ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {

        val position: Int = parent.getChildAdapterPosition(view) - if (isHeader) 1 else 0
        if (isHeader && position < 0)
            return
        val column: Int = position % spanCount
        if (includeEdge) {
            outRect.left =
                spacing - column * spacing / spanCount
            outRect.right =
                (column + 1) * spacing / spanCount
            if (position < spanCount) {
                outRect.top = spacing
            }
            outRect.bottom = spacing
        } else {
            outRect.left = column * spacing / spanCount
            outRect.right =
                spacing - (column + 1) * spacing / spanCount
            if (position - 1 >= spanCount) {
                outRect.top = spacing
            }
        }
    }

}